package my.jpcap.my;

import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;

public class MyTcpdump {
	private static ExecutorService pool = Executors.newCachedThreadPool();

	public synchronized static MyTcpdump ins() {
		if (null == tcpdump) {
			tcpdump = new MyTcpdump();
			tcpdump.init();
		}
		return tcpdump;

	}

	public Map<String, Integer> getNameTrafficMap() {
		return nameTrafficMap;
	}

	private void init() {
		try {
			InetAddress address = InetAddress.getLocalHost();
			System.out.println(address.getHostAddress());

			final NetworkInterface[] devices = JpcapCaptor.getDeviceList();
			for (int i = 0; i < devices.length; i++) {
				NetworkInterface nc = devices[i];
				if (nc.addresses.length > 0) {
					String addr = nc.addresses[0].address.toString();
					JpcapCaptor jpcap = JpcapCaptor.openDevice(nc, 5000, true,
							20);
					jpcap.setFilter("src host " + address.getHostAddress(), true);
					jpcap.setFilter("dst host 192.168.0.205", true);

					LoopPacketThread lt = new LoopPacketThread(jpcap, addr);
					// pool.submit(lt);
					lt.start();
					System.out.println(addr + "上的采集线程己启动************");
				}
			}
		} catch (Exception ef) {
			ef.printStackTrace();
			System.out.println("start caputerThread error ! ! ! !" + ef);
		}
	}

	void putNetValue(String name, int value) {
		if (nameTrafficMap.containsKey(name)) {
			value = nameTrafficMap.get(name) + value;
			nameTrafficMap.put(name, value);
		} else {
			nameTrafficMap.put(name, value);
		}
	}

	private MyTcpdump() {
	}

	private Map<String, Integer> nameTrafficMap = new java.util.HashMap();
	// 单实例
	private static MyTcpdump tcpdump = null;

	public static void main(String args[]) throws InterruptedException {
		MyTcpdump.ins();

		Thread.sleep(10000);
		LoopPacketThread.setContinueLoop(false);
		System.out.println("***********最后统计到的数据************");
		System.out.println(MyTcpdump.ins().getNameTrafficMap());
		// pool.shutdownNow();
	}

}
